<script setup>
import { ref, onMounted, reactive, watch, computed } from 'vue';
import {
    reqAllTeacherDetail,
    reqPsyTeacherApplyContent,
    reqLeaveTime,
    reqSuccessTime,
    reqAddPsychologNote
} from '@/api/student/index';
import { ElMessage } from 'element-plus';
import {
    RESERVATION_TIEM,
    CHEKC_WEEK_FN_MAP
} from '@/utils/checkWeekNumber.js';

const PUBLIC_URL = import.meta.env.VITE_APP_IMAGE_URL;

const teachersDetail = ref([]);

const isShowdrawer = ref(false);

const isLoading = ref(false);

const getAllTeacher = async () => {
    try {
        const result = await reqAllTeacherDetail();

        if (result.status == 200) {
            teachersDetail.value = result.dataList;
        } else {
            throw new Error(result.statusText || '获取不到老师信息');
        }
    } catch (e) {
        ElMessage.error(e.message);
    }
};

onMounted(() => {
    getAllTeacher();
});

const getPsychologyTeacher = async () => {
    try {
        const result = await reqPsyTeacherApplyContent(psychologyNote.id);

        psychologyNote.place = result.data.place;
    } catch (e) {
        ElMessage.error(e.message || '老师信息获取失败');
    }
};

// 点击预约按钮所执行的回调函数
const apply = async ({ teaNum, teaName }) => {
    isLoading.value = true;
    psychologyNote.id = teaNum;
    psychologyNote.teacher = teaName;
    psychologyNote.phoneNumber = '';
    psychologyNote.place = '';
    psychologyNote.bornDate = '';
    psychologyNote.content = '';
    psychologyNote.bookDate = '';
    psychologyNote.time = '';
    psychologyNote.isEmergency = 0;
    await getPsychologyTeacher();
    isLoading.value = false;
    isShowdrawer.value = true;
};

// 表单数据
const psychologyNote = reactive({
    id: '',
    teacher: '',
    phoneNumber: '',
    place: '',
    bornDate: '',
    content: '',
    bookDate: '',
    time: '',
    isEmergency: 0
});

// 日期发生变化时 预约时间也要跟着改版
watch(
    () => psychologyNote.bookDate,
    () => {
        psychologyNote.time = '';
        setTimeOption();
    }
);

const timeOptions = ref([]);

// 修改时间选项
const setTimeOption = async () => {
    let finalOptions = [];

    if (psychologyNote.id && psychologyNote.bookDate) {
        const day = new Date(psychologyNote.bookDate).getDay();
        const { timeSlot } = RESERVATION_TIEM.get(psychologyNote.id);
        const timeArr = timeSlot[day];

        const { dataList } = await reqSuccessTime(
            psychologyNote.id,
            psychologyNote.bookDate
        );

        if (dataList.length == 0) {
            finalOptions = timeArr;
        } else {
            finalOptions = timeArr
                .map(
                    option =>
                        `${psychologyNote.bookDate} ${option.split('-')[0]}`
                )
                .filter(optionTime => {
                    let flag = false;

                    for (let item of dataList) {
                        const successTime = dateFormat(
                            item,
                            'yyyy/MM/dd HH:mm'
                        );
                        // console.log(successTime);
                        // console.log(optionTime);
                        console.log(successTime);
                        flag = successTime == optionTime;
                    }

                    return !flag;
                });
        }

        const { dataList: leaveList } = await reqLeaveTime(psychologyNote.id);
        const resultList = leaveList.map(value => value.Leave_time);

        if (resultList.length !== 0) {
            finalOptions = finalOptions
                .map(
                    option =>
                        `${psychologyNote.bookDate.replace(/\//g, '-')} ${
                            option.split(' ')[1] || option
                        }`
                )
                .filter(optionTime => {
                    const flag = resultList.includes(optionTime);
                    return !flag;
                });
        }

        timeOptions.value = finalOptions;
    }
};

const timeSelectPlacholder = computed(() => {
    if (!psychologyNote.bookDate) {
        return '请先选择预约日期';
    } else if (timeOptions.value == 0) {
        return '当前日期,并没有时间提供预约';
    } else {
        return '请选择日期';
    }
});

// format
const dateFormat = (dateString, format) => {
    const date = new Date(dateString);
    date.setHours(date.getHours() - 14);
    const o = {
        'M+': date.getMonth() + 1, //month
        'd+': date.getDate(), //day
        'H+': date.getHours(), //hour
        'm+': date.getMinutes(), //minute
        's+': date.getSeconds(), //second
        'q+': Math.floor((date.getMonth() + 3) / 3), //quarter
        S: date.getMilliseconds() //millisecond
    };
    if (/(y+)/.test(format))
        format = format.replace(
            RegExp.$1,
            (date.getFullYear() + '').substr(4 - RegExp.$1.length)
        );
    for (let k in o)
        if (new RegExp('(' + k + ')').test(format))
            format = format.replace(
                RegExp.$1,
                RegExp.$1.length == 1
                    ? o[k]
                    : ('00' + o[k]).substr(('' + o[k]).length)
            );
    return format;
};

// 检查出生日期
const checkBornDate = (rule, value, callback) => {
    if (value == '') {
        callback(new Error('请选择出生日期'));
    } else {
        if (new Date(value) >= Date.now()) {
            callback(new Error('请不要超出今天日期'));
            return;
        }
        callback();
    }
};

// 检查申请日期
const validatorBookDate = (rule, value, callback) => {
    if (value == '') {
        callback(new Error('请选择申请日期'));
        return;
    }
    if (!CHEKC_WEEK_FN_MAP[psychologyNote.id](value)) {
        callback(new Error('请选择有绿色圆圈的日期'));
        return;
    }
    const selectDate = new Date(value);
    const nowDate = new Date();

    nowDate.setDate(nowDate.getDate() - 1);

    if (selectDate <= nowDate) {
        callback(new Error('请不要选择当前日期以前的日期'));
        return;
    }

    callback();
};

// 校验
const formRule = reactive({
    phoneNumber: [
        { required: true, message: '手机号不能为空', trigger: 'blur' }
    ],
    content: [{ required: true, message: '资讯内容不能为空', trigger: 'blur' }],
    bornDate: [
        {
            validator: checkBornDate,
            trigger: 'change',
            type: 'date'
        }
    ],
    bookDate: [
        {
            validator: validatorBookDate,
            trigger: 'change',
            type: 'date'
        }
    ],
    time: [{ required: true, message: '请选择时间选项', trigger: 'change' }]
});

// form ref
const formRef = ref(null);

// 点击申请触发回调函数
const submitNote = async formEl => {
    if (!formEl) return;
    await formEl.validate(valid => {
        if (valid) {
            updatePsychologyNote();
        }
    });
};

const updatePsychologyNote = async () => {
    const { id, phoneNumber, bornDate, content, time, isEmergency } =
        psychologyNote;

    const timeArr = time.split('-');

    const startTime = `${timeArr[0]}-${timeArr[1]}-${timeArr[2]}`;
    const endTime = `${startTime.split(' ')[0]} ${timeArr[3]}`;

    const data = {
        userPhone: phoneNumber,
        startTime: startTime,
        endTime: endTime,
        place: id,
        reason: content,
        teacherNum: id,
        userBirthday: `${bornDate.replace(/\//g, '-')} 00:00:00`,
        urgentState: isEmergency.toString()
    };

    const result = await reqAddPsychologNote(data);
    if (result.resultCode === '200') {
        ElMessage({
            type: 'success',
            message: '申请成功'
        });
        isShowdrawer.value = false;
    }
    console.log(result);
};
</script>

<template>
    <div class="container">
        <ul class="teacher-wrapper" v-loading="isLoading">
            <li
                class="item"
                v-for="{
                    bizAppointmentTeacher: info,
                    labelList
                } in teachersDetail"
                :key="info.teaNum"
            >
                <div class="picture-wrap">
                    <img
                        class="picture"
                        :src="PUBLIC_URL + info.icon"
                        :alt="info.teaName"
                    />
                </div>
                <div class="info">
                    <div class="info__head">{{ info.teaName }}</div>
                    <ul class="labelList">
                        <li
                            class="label"
                            v-for="(label, index) in labelList"
                            :key="index"
                        >
                            {{ label }}
                        </li>
                    </ul>
                    <p class="info__text">
                        {{ info.centect }}
                    </p>
                    <div class="apply-btn-wrapper">
                        预约时间:
                        <span>
                            {{ RESERVATION_TIEM.get(info.teaNum).time }}
                        </span>
                        <el-button
                            class="apply"
                            type="success"
                            @click="apply(info)"
                        >
                            预约
                        </el-button>
                    </div>
                </div>
            </li>
        </ul>
        <el-drawer
            v-model="isShowdrawer"
            size="85%"
            :with-header="false"
            :destroy-on-close="true"
        >
            <el-form
                label-position="top"
                ref="formRef"
                :model="psychologyNote"
                :rules="formRule"
            >
                <el-form-item>
                    <div class="teacher">
                        预约老师: {{ psychologyNote.teacher }}
                    </div>
                </el-form-item>
                <el-form-item>
                    <div class="teacher">
                        资讯地点: {{ psychologyNote.place }}
                    </div>
                    <span style="color: red">
                        (18点后的咨询地点为晚间心理咨询室(学生服务中心A03))
                    </span>
                </el-form-item>
                <el-form-item label="手机号" prop="phoneNumber">
                    <el-input
                        placeholder="请输入手机号"
                        v-model="psychologyNote.phoneNumber"
                    ></el-input>
                </el-form-item>
                <el-form-item label="资讯内容" prop="content">
                    <el-input
                        placeholder="咨询内容简述或个人心理感受简述"
                        v-model="psychologyNote.content"
                    ></el-input>
                </el-form-item>
                <el-form-item label="出生日期" prop="bornDate">
                    <el-date-picker
                        v-model="psychologyNote.bornDate"
                        type="date"
                        format="YYYY/MM/DD"
                        value-format="YYYY/MM/DD"
                        placeholder="请选择出生日期"
                    ></el-date-picker>
                </el-form-item>
                <el-form-item label="预约日期" prop="bookDate">
                    <el-date-picker
                        v-model="psychologyNote.bookDate"
                        type="date"
                        placeholder="选择日期"
                        format="YYYY/MM/DD"
                        value-format="YYYY/MM/DD"
                    >
                        <template #default="cell">
                            <div class="date-cell">
                                <span
                                    class="date-text"
                                    :class="{
                                        'select-available': CHEKC_WEEK_FN_MAP[
                                            psychologyNote.id
                                        ](cell.dayjs.$d)
                                    }"
                                >
                                    {{ cell.text }}
                                </span>
                            </div>
                        </template>
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="预约时间" prop="time">
                    <el-select
                        v-model="psychologyNote.time"
                        :disabled="!psychologyNote.bookDate?.length"
                        :placeholder="timeSelectPlacholder"
                    >
                        <el-option
                            v-for="option in timeOptions"
                            :key="option"
                            :value="option"
                            :label="option"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="预约类别" prop="isEmergency">
                    <el-radio-group
                        v-model="psychologyNote.isEmergency"
                        size="large"
                    >
                        <el-radio-button :label="0">一般</el-radio-button>
                        <el-radio-button :label="1">紧急</el-radio-button>
                    </el-radio-group>
                </el-form-item>
                <el-form-item>
                    <el-button
                        size="large"
                        type="primary"
                        @click="submitNote(formRef)"
                    >
                        确定申请
                    </el-button>
                </el-form-item>
            </el-form>
        </el-drawer>
    </div>
</template>

<style scoped lang="scss">
.container {
    font-size: 16rem;
    background-color: rgb(247, 247, 247);
}

.teacher-wrapper {
    display: flex;
    flex-direction: column;

    .item {
        display: flex;
        width: 100%;
        border-bottom: 1px solid #aaa;
        padding: 10rem 20rem;
    }
}

.picture-wrap {
    width: 70rem;

    .picture {
        width: 70rem;
        height: 70rem;
        border-radius: 40rem;
        object-fit: cover;
        border: 3px solid rgb(95, 187, 95);
    }
}

.info {
    padding-top: 6rem;
    margin-left: 10rem;

    .date__head {
        font-size: 18rem;
        font-weight: bold;
        margin-bottom: 6rem;
    }

    .labelList {
        display: flex;
        flex-wrap: wrap;
        font-size: 12rem;
        color: rgb(139, 154, 35);
        margin-bottom: 10rem;

        .label {
            padding: 3rem 8rem;
            margin: 2rem;
            background-color: rgb(238, 238, 238);
            border-radius: 10px;
        }
    }

    &__text {
        font-size: 14rem;
        color: #666;
        margin-bottom: 10rem;
    }

    .apply-btn-wrapper {
        align-items: center;
        display: flex;
        font-size: 14rem;
        color: #666;

        .apply {
            margin-left: auto;
            padding: 0 20rem;
        }
    }
}

.drawer__title {
    font-size: 16rem;
    font-weight: bold;
}

.teacher {
    font-size: 16rem;
    font-weight: bold;
}
.date-cell {
    height: 30px;
    padding: 3px 0;
    box-sizing: border-box;
}

.date-cell .date-text {
    width: 24px;
    height: 24px;
    display: block;
    margin: 0 auto;
    line-height: 24px;
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
    border-radius: 50%;
}

.date-cell .select-available {
    background: rgb(151, 210, 151);
    color: rgb(88, 88, 26);
}
</style>
